package artid.com.arttogoa;

import java.util.ArrayList;
import java.util.List;

import artid.com.arttogoa.R;

import artid.com.arttogoa.adapter.ArtDynamicDetailAdapter;
import artid.com.arttogoa.adapter.ArtImageFragmentAdapter;
import artid.com.arttogoa.barcode.Cache;
import artid.com.arttogoa.parser.AppItem;
import artid.com.arttogoa.parser.ArtDynamicComment;
import artid.com.arttogoa.parser.ArtDynamicDetail;
import artid.com.arttogoa.parser.RecordDetailList;
import artid.com.arttogoa.photo.ImagePagerActivity;
import artid.com.arttogoa.task.CallbackSky;
import artid.com.arttogoa.view.MyListView;
import artid.com.arttogoa.view.SubViewPager;
import artid.com.arttogoa.view.pulltorefresh.pullableview.PullToRefreshLayout;
import artid.com.arttogoa.view.pulltorefresh.pullableview.PullableScrollView;
import artid.com.arttogoa.volley.BitmapCache;
import artid.com.arttogoa.volley.VolleyBasic;
import artid.com.arttogoa.volley.VolleyCallback;
import artid.com.arttogoa.volley.VolleyData;
import artid.com.arttogoa.volley.VolleyMap;
import com.android.volley.RequestQueue;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;
import com.android.volley.toolbox.ImageLoader.ImageListener;
import com.umeng.socialize.utils.Log;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.support.v7.widget.ShareActionProvider;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

/**
 * 
 private Md5FileNameGenerator s;
 * 
 * 项目名称：ArtworkArtA 类名称：ArtDynamicDetailActivity 类描述：艺术品动态详情 创建人：耿卫斌
 * 创建时间：2016年5月16日 下午1:23:27
 * 
 */
public class ArtDynamicDetailActivity extends BaseActivity implements
OnClickListener, OnTouchListener {
	private MyListView mListview;
	private ArtDynamicDetailAdapter mAdapter;
	private Context mContext;
	private String id;
	private ShareActionProvider shartAction;
	private ImageView art_img, redetail_complete;
	private ImageLoader mImageLoader;
	private LinearLayout renzhengLayout, hint;
	private TextView dynamiccode, realname, spc, age, detail;
	public PopupWindow window;
	private PullToRefreshLayout mPullLayout;
	private PullableScrollView mScrollView;
	private boolean isRefreshed = false;// 是否刷新
	private int page = 1;
	private List<ArtDynamicComment> list;
	private List<ArtDynamicComment> more_list;
	View slideMain;
	private LinearLayout artInfo;
	private RelativeLayout banndRL;
	private ArtDynamicDetail item;//请求到的所有值

	/**
	 * 轮播
	 */
	private SubViewPager mViewPager;
	private ArrayList<View> pageview;
	// 主适配器
	private ArtImageFragmentAdapter mFragmentAdapter;
	private RelativeLayout r1, r2, r3;
	private ImageView iv1, iv2, iv3;
	private List<ImageView> images;
	private List<RecordDetailList.Pointinformation> list_Pointinformation;//轮播跳转用的微观图

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_art_dynamicdetail);
		setContent(this, getIntent());
		initView();
	}

	private void initView() {
		mContext = this;
		setBack();
		// 注册当前广播
		IntentFilter filter = new IntentFilter("com.Push.receiver");
		registerReceiver(broadcastReceiver, filter);
		id = getIntent().getExtras().getString("id");
		type = getIntent().getExtras().getString("type");
		artInfo = (LinearLayout) findViewById(R.id.ll_artrec);
		if (type != null && type.equals("2")) {
			artInfo.setVisibility(View.GONE);
		}
		list = new ArrayList<ArtDynamicComment>();
		more_list = new ArrayList<ArtDynamicComment>();
		list_Pointinformation=new ArrayList<RecordDetailList.Pointinformation>();
		RequestQueue mQueue = Volley.newRequestQueue(mContext);
		mImageLoader = new ImageLoader(mQueue, new BitmapCache());
		mTittle = (TextView) findViewById(R.id.title_text);
		art_img = (ImageView) findViewById(R.id.iv_art_img);
		redetail_complete = (ImageView) findViewById(R.id.redetail_complete);
		mBack.setOnClickListener(this);
		renzhengLayout = (LinearLayout) findViewById(R.id.renzheng_layout);
		mListview = (MyListView) findViewById(R.id.art_dynamic_detail_list);
		dynamiccode = (TextView) findViewById(R.id.dynamic_code);
		realname = (TextView) findViewById(R.id.dynamic_name);
		spc = (TextView) findViewById(R.id.dynamic_spc);
		age = (TextView) findViewById(R.id.dynamic_age);
		detail = (TextView) findViewById(R.id.dynamic_detail);
		mPullLayout = (PullToRefreshLayout) findViewById(R.id.artdynamicdetail_pulltorefreshlayout);
		mScrollView = (PullableScrollView) findViewById(R.id.artdynamicdetail_pullablescrollview);
		mScrollView.smoothScrollTo(0, 0);
		mPullLayout.setOnRefreshListener(new PullToRefreshLayout.OnRefreshListener() {
			@Override
			public void onRefresh(PullToRefreshLayout pullToRefreshLayout) {
				// TODO Auto-generated method stub
				page = 1;
				isRefreshed = true;
				reqArtDynamicComment();
			}

			@Override
			public void onLoadMore(PullToRefreshLayout pullToRefreshLayout) {
				// TODO Auto-generated method stub
				// pullToRefreshLayout.setBottomDismiss();
				page++;
				reqArtDynamicComment();
			}
		});
		reqArtDynamicDetail();
		reqArtDynamicComment();
	}

	private static List<ImageView> dotViewList;
	ArrayList<String> imgFocusList, urlFocusList;

	void initSlide() {

	}

	private void reqArtDynamicComment() {
		VolleyBasic.getInstance(ArtDynamicDetailActivity.this).post(
				Cache.artcomment,
				VolleyMap.getInstance().artComment(id, page + "", "10"),
				ArtDynamicComment.class, new VolleyCallback() {

					@Override
					public void onSuccess(VolleyData vd) {
						mPullLayout.loadmoreFinish(mPullLayout.SUCCEED);
						list = (List<ArtDynamicComment>) vd.getList();
						if (isRefreshed == true) {
							more_list.clear();
							isRefreshed = false;
						}
						if (!list.isEmpty()) {
							more_list.addAll(list);
						}
						if (mAdapter == null) {
							mAdapter = new ArtDynamicDetailAdapter(mContext);
							mListview.setAdapter(mAdapter);
						}
						mAdapter.setdata(more_list);
						mAdapter.notifyDataSetChanged();
						mListview
						.setOnItemClickListener(new OnItemClickListener() {

							@Override
							public void onItemClick(
									AdapterView<?> arg0, View arg1,
									int arg2, long arg3) {
								// TODO Auto-generated method stub
								showPopwindow(mContext, arg1,
										R.id.comment_content,
										mAdapter.listdata.get(arg2)
										.getId(),
										mAdapter.listdata.get(arg2)
										.getNickname());
							}
						});
					}

					@Override
					public void onError(VolleyError volleyError) {

					}
				});
	}

	private String type;

	private void reqArtDynamicDetail() {
		VolleyBasic.getInstance(ArtDynamicDetailActivity.this).post(
				Cache.artworkinfo, VolleyMap.getInstance().artworkDynamic(id),
				ArtDynamicDetail.class, new VolleyCallback() {

					@Override
					public void onSuccess(VolleyData vd) {
						item = (ArtDynamicDetail) vd.getData();
						slideMain = (View) findViewById(R.id.slideView);

						if (item.getList() == null) {
							slideMain.setVisibility(View.GONE);
							ImageListener listener = ImageLoader
									.getImageListener(art_img,
											R.drawable.yspba_img_mor,
											R.drawable.yspba_img_mor);
							mImageLoader.get(item.getImgurl(), listener);
						} else {
							LinearLayout dotLayout = (LinearLayout) findViewById(R.id.dotLayout);
							dotViewList = new ArrayList<ImageView>();
							ImageView iv1 = (ImageView) findViewById(R.id.iv_carousel1);
							imgFocusList = new ArrayList<String>();
							urlFocusList = new ArrayList<String>();
							slideMain.setVisibility(View.VISIBLE);
							String imgarrstr = "";
							for (ArtDynamicDetail.ImageData index : item
									.getList()) {
								String imgString = index.getImgurl();
								imgFocusList.add(imgString);
								urlFocusList.add(imgString);
								imgarrstr += (index.getImgurl() + ",");
								// dotLayout.addView(iv1);
								dotViewList.add(iv1);
							}
							String[] arrImg = imgarrstr.split(",");
							int num;
							if(item.getList().size()>=3){
								num=3;
							}else{
								num=item.getList().size();
							}
							for (int i = 0; i < num; i++) {
								RecordDetailList.Pointinformation bean=new RecordDetailList.Pointinformation();
								bean.setImgurl(item.getList().get(i).getImgurl());
								bean.setText(item.getList().get(i).getText());
								list_Pointinformation.add(bean);
							}
							initViewPager(list_Pointinformation);
						}
						mTittle.setText(item.getTitle());
						String code = item.getIs_auth();
						if (code.equals("2")) {
							renzhengLayout.setVisibility(View.VISIBLE);
							dynamiccode.setText("认证编号：" + item.getCode());
							redetail_complete.setVisibility(View.VISIBLE);
						}
						realname.setText(item.getRealname());
						spc.setText(item.getSpec());
						age.setText(item.getAge() + "年");
						detail.setText(item.getDetail());
					}

					@Override
					public void onError(VolleyError volleyError) {

					}
				});

	}

	@Override
	public void onClick(View v) {

	}

	/**
	 * 回复
	 */
	private void postReply(String id, final String content) {
		VolleyBasic.getInstance(this).post(Cache.replyComment,
				VolleyMap.getInstance().replyComment(id, content),
				AppItem.class, new VolleyCallback() {
			public void onSuccess(VolleyData vd) {
				// TODO Auto-generated method stub
				System.out.println(vd.getJson());
				if (vd.getCode() == VolleyData.Success) {
					Intent i = new Intent("com.Push.receiver");
					mContext.sendBroadcast(i);
					reqArtDynamicComment();
				}
			}

			public void onError(VolleyError volleyError) {

			}
		});
	}



	/**
	 * 
	 */
	@SuppressWarnings("deprecation")
	// 记录开始手指点击的位置,和滑动的X距离
	private void initViewPager(List<RecordDetailList.Pointinformation> list) {
		// TODO Auto-generated method stub
		r1 = (RelativeLayout) findViewById(R.id.ll_carousel1);
		r2 = (RelativeLayout) findViewById(R.id.ll_carousel2);
		r3 = (RelativeLayout) findViewById(R.id.ll_carousel3);
		images = new ArrayList<ImageView>();
		iv1 = (ImageView) findViewById(R.id.iv_carousel1);
		iv2 = (ImageView) findViewById(R.id.iv_carousel2);
		iv3 = (ImageView) findViewById(R.id.iv_carousel3);
		images.add(iv1);
		images.add(iv2);
		images.add(iv3);
		mViewPager = (SubViewPager) findViewById(R.id.viewPager);
		banndRL=(RelativeLayout) findViewById(R.id.ArtDynamicDetail_banndRL);
		mFragmentAdapter = new ArtImageFragmentAdapter(
				getSupportFragmentManager(), new CallbackSky() {

					@Override
					public void callBack(int index) {
						imageCom();
					}
				});
		mFragmentAdapter.setData(list);
		mFragmentAdapter.notifyDataSetChanged();
		mViewPager.setAdapter(mFragmentAdapter);
		mViewPager.setOnTouchListener(this);
		mViewPager.setOffscreenPageLimit(list.size());
		mViewPager.setOnPageChangeListener(mOnPageChangeListener);
		mViewPager.setCurrentItem(0);
		changeImage(0);

	}

	private int startX = 0;//手指按下的初始位置
	private int startY=0;
	private boolean start = true;

	@Override
	public boolean dispatchTouchEvent(MotionEvent event) {
		// 一定要spuer，否则事件打住,不会在向下调用了
		super.dispatchTouchEvent(event);
		switch (event.getAction()) {
		// 记录用户手指点击的位置
		case MotionEvent.ACTION_DOWN:
			PullableScrollView.isSlide=false;
			startX = (int) event.getX();
			startY = (int) event.getY();
			break;
		case MotionEvent.ACTION_UP:
			PullableScrollView.isSlide=true;
			break;
		case MotionEvent.ACTION_MOVE:
			//判断是否有轮播图
			if(banndRL!=null){
				//判断是否在滑动广告
				if(startY<banndRL.getHeight() && ((startX - event.getX()) > 0 || (startX-event.getX()) < 0)){
					PullableScrollView.isSlide=false;
				}else{
					PullableScrollView.isSlide=true;
				}
			}else{
				PullableScrollView.isSlide=true;
			}
			break;
		}

		return true;// return false,继续向下传递，return true;拦截,不向下传递
	}

	// 默认是重写onTouch事件
	@Override
	public boolean onTouch(View v, MotionEvent event) {
		switch (event.getAction()) {
		case MotionEvent.ACTION_DOWN:
			PullableScrollView.isSlide=false;
			startX = (int) event.getX();
			break;
		case MotionEvent.ACTION_UP:
			PullableScrollView.isSlide=true;
			//			Log.d("log", "手指已抬起");
			break;
		case MotionEvent.ACTION_MOVE:
			if ((startX - event.getX()) > 50 && (currentIndex == list_Pointinformation.size() - 1)) {
				if (start) {
					imageBrower();
					start = false;
				}
			}
			break;

		default:
			break;
		}
		return false;
	}

	/*
	@Override
	public boolean onTouch(View v, MotionEvent event) {
		switch (event.getAction()) {
		case MotionEvent.ACTION_DOWN:
			lastX = (int) event.getX();
			break;
		case MotionEvent.ACTION_MOVE:
			if ((lastX - event.getX()) > 100 && (currentIndex == list_Pointinformation.size() - 1)) {
				if (start) {
//					imageBrower();
					start = false;
				}
				// Toast.makeText(this, "在此处添加界面跳转代码哦！",
				// Toast.LENGTH_LONG).show();
				// this.finish();
			}
			break;
		default:
			break;
		}
		return false;
	}*/

	@Override
	protected void onRestart() {
		// TODO Auto-generated method stub
		if (currentIndex == list_Pointinformation.size() - 1)
			start = true;
		super.onRestart();
		// start = true;
	}

	private int currentIndex;
	private OnPageChangeListener mOnPageChangeListener = new OnPageChangeListener() {
		@Override
		public void onPageSelected(int pos) {
			currentIndex = pos;
			if (currentIndex == list_Pointinformation.size() - 1)
				start = true;
			changeImage(pos);
		}

		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {

		}

		@Override
		public void onPageScrollStateChanged(int pos) {
			System.out.println("positionStateChanged=" + pos);
			if(pos!=0){
				PullableScrollView.isSlide=false;
			}else{
				PullableScrollView.isSlide=true;
			}
		}
	};

	protected void changeImage(int index) {
		// TODO Auto-generated method stub
		for (int i = 0; i < images.size(); i++) {
			if (i == index) {
				images.get(i).setImageResource(R.drawable.point_pressed);
			} else {
				images.get(i).setImageResource(R.drawable.point_unpressed);
			}
		}
	}

	/**
	 * 打开完整图查看图片
	 * 
	 * @param position
	 * @param urls2
	 */
	protected void imageCom() {
		ArrayList<String> urls = new ArrayList<String>();
		for (int i = 0; i < list_Pointinformation.size(); i++) {
			urls.add(list_Pointinformation.get(i).getImgurl());
		}
		Intent intent = new Intent(mContext, ImagePagerActivity.class);
		// 图片url,为了演示这里使用常量，一般从数据库中或网络中获取
		intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_URLS, urls);
		intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_INDEX, currentIndex);
		intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_TYPE,
				ImagePagerActivity.LATTICE);
		mContext.startActivity(intent);
	}


	/**
	 * 打开微观图查看图片
	 * 
	 * @param position
	 * @param urls2
	 */
	protected void imageBrower() {
		RecordDetailList data=new RecordDetailList();
		ArrayList<RecordDetailList.Pointinformation> list = new ArrayList<RecordDetailList.Pointinformation>();
		for (int i = 0; i < item.getList().size(); i++) {
			RecordDetailList.Pointinformation bean=new RecordDetailList.Pointinformation();
			bean.setImgurlone(item.getList().get(i).getImgurlone());
			bean.setText(item.getList().get(i).getText());
			list.add(bean);
			data.setPointinformation(list);
		}
		Intent intent = new Intent(mContext, ImagePagerActivity.class);
		// 图片url,为了演示这里使用常量，一般从数据库中或网络中获取
		intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_URLS, data);
		intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_TYPE,ImagePagerActivity.MICSHOW);
		intent.putExtra("intentType", 2);//手机备案
		mContext.startActivity(intent);
	}

	public void showPopwindow(final Context mContext, View v, int ViewId,
			final String id, String hint) {
		// 利用layoutInflater获得View
		LayoutInflater inflater = (LayoutInflater) mContext
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View view = inflater.inflate(R.layout.popupwindow_comment, null);
		// 下面是两种方法得到宽度和高度 getWindow().getDecorView().getWidth()
		window = new PopupWindow(view, WindowManager.LayoutParams.MATCH_PARENT,
				WindowManager.LayoutParams.WRAP_CONTENT);
		// 设置popWindow弹出窗体可点击，这句话必须添加，并且是true
		window.setFocusable(true);
		window = new PopupWindow(view, WindowManager.LayoutParams.FILL_PARENT,
				WindowManager.LayoutParams.WRAP_CONTENT, false);
		// 设置可以获取焦点，否则弹出菜单中的EditText是无法获取输入的
		window.setFocusable(true);
		// 这句是为了防止弹出菜单获取焦点之后，点击activity的其他组件没有响应
		window.setBackgroundDrawable(new BitmapDrawable());
		// 防止虚拟软键盘被弹出菜单遮住
		window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
		// 在底部显示
		window.showAtLocation(v.findViewById(ViewId), Gravity.BOTTOM, 0, 0);
		// 这里检验popWindow里的button是否可以点击
		showKeyboard(mContext);
		TextView first = (TextView) view
				.findViewById(R.id.popupwindow_comment_Button);
		final EditText mEditText = (EditText) view
				.findViewById(R.id.popupwindow_comment_mEditText);
		mEditText.setHint("回复:" + hint);
		first.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Log.d("log", "第一个按钮被点击了");
				postReply(id, mEditText.getText().toString());
				window.dismiss();
			}
		});
		// popWindow消失监听方法
		window.setOnDismissListener(new OnDismissListener() {

			@Override
			public void onDismiss() {
				System.out.println("popWindow消失");
				showKeyboard(mContext);
			}
		});
	}

	public static void showKeyboard(Context mContext) {
		InputMethodManager imm = (InputMethodManager) mContext
				.getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
	}

	// 对开始接单的广播监听
	BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			if ("1".equals(intent.getStringExtra("PushType"))) {
				// 只要不等于0就是回复推送
				id = MainActivity.PushMessage.get("art_id");
				mAdapter = null;
				page = 1;
				isRefreshed = true;
				reqArtDynamicComment();
			}
		}
	};

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		// 清空推送
		MainActivity.PushMessage = null;
		// 关闭广播
		unregisterReceiver(broadcastReceiver);
	}
}
